package com.sgai.zero_robot.widget;


import static com.sgai.zero_robot.utils.ZeroUtils.getInstall;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.sgai.zero_robot.R;
import com.sgai.zero_robot.database.ZeroDetectionEntity;
import com.sgai.zero_robot.pojo.BunchInfo;
import com.sgai.zero_robot.pojo.InstallInfo;
import com.sgai.zero_robot.pojo.PhaseInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TableView extends FrameLayout {

    private TableLayout tableRoot;
    private TextView tvLineName;
    private TextView tvTowerNum;
    private TextView tvInstall;
    private TextView tvCollectTitle;
    private TextView tvCollectContent;
    private TextView tvAddress;

    public TableView(@NonNull Context context) {
        this(context,null);
    }

    public TableView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,-1);
    }

    public TableView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        View inflate = View.inflate(context, R.layout.view_table, this);
        tableRoot = inflate.findViewById(R.id.table_root);
        tvLineName = inflate.findViewById(R.id.tv_line_name);
        tvTowerNum = inflate.findViewById(R.id.tv_tower_num);
        tvInstall = inflate.findViewById(R.id.tv_install);
        tvCollectTitle = inflate.findViewById(R.id.tv_collect_title);
        tvCollectContent = inflate.findViewById(R.id.tv_collect_content);
        tvAddress = inflate.findViewById(R.id.tv_address);
    }
    public void setDate(InstallInfo installInfo){
        if (TextUtils.isEmpty(installInfo.lineName)){
            tvLineName.setText("未知");
        }else{
            tvLineName.setText(installInfo.lineName);
        }
        if (TextUtils.isEmpty(installInfo.towerName)){
            tvTowerNum.setText("未知");
        }else{
            tvTowerNum.setText(installInfo.towerName);
        }
        if (installInfo.install<=0){
            tvInstall.setText("未知");
        }else{
            tvInstall.setText(getInstall(installInfo.install));
        }
        String address = installInfo.province+installInfo.city;
        if (TextUtils.isEmpty(address)){
            tvAddress.setText("未知");
        }else{
            tvAddress.setText(address);
        }
        //开始整理数据
        disposalData(installInfo.phaseInfos);
    }

    private void clearContent(){
        int childCount = tableRoot.getChildCount();
        if (childCount>5){
            tableRoot.removeViewAt(5);
            clearContent();
        }
    }
    private void disposalData(List<PhaseInfo> phaseInfos){
        clearContent();
        if (phaseInfos == null||phaseInfos.size()<=0){
            if (tableCallback!=null){
                tableCallback.onFInish();
            }
            return;
        }
        //处理相位
        disposalPhase(phaseInfos);
        //到这里 应该会有9个列表 每个列表的长度相等
        List<ZeroDetectionEntity> one = phaseInfos.get(0).insulatorInfos.get(0).insulatorInfos;
        List<ZeroDetectionEntity> two = phaseInfos.get(0).insulatorInfos.get(1).insulatorInfos;
        List<ZeroDetectionEntity> three = phaseInfos.get(0).insulatorInfos.get(2).insulatorInfos;

        List<ZeroDetectionEntity> four = phaseInfos.get(1).insulatorInfos.get(0).insulatorInfos;
        List<ZeroDetectionEntity> five = phaseInfos.get(1).insulatorInfos.get(1).insulatorInfos;
        List<ZeroDetectionEntity> six = phaseInfos.get(1).insulatorInfos.get(2).insulatorInfos;

        List<ZeroDetectionEntity> seven = phaseInfos.get(2).insulatorInfos.get(0).insulatorInfos;
        List<ZeroDetectionEntity> eight = phaseInfos.get(2).insulatorInfos.get(1).insulatorInfos;
        List<ZeroDetectionEntity> nine = phaseInfos.get(2).insulatorInfos.get(2).insulatorInfos;
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                List<Integer> sb1 = new ArrayList<>();
                List<Integer> sb2 = new ArrayList<>();
                List<Integer> sb3 = new ArrayList<>();
                List<Integer> sb4 = new ArrayList<>();
                List<Integer> sb5 = new ArrayList<>();
                List<Integer> sb6 = new ArrayList<>();
                List<Integer> sb7 = new ArrayList<>();
                List<Integer> sb8 = new ArrayList<>();
                List<Integer> sb9 = new ArrayList<>();
                for (int i = 0;i<one.size();i++){
                    addRow(String.valueOf(i+1),getContent(one.get(i).getState())
                            ,getContent(two.get(i).getState())
                            ,getContent(three.get(i).getState())
                            ,getContent(four.get(i).getState())
                            ,getContent(five.get(i).getState())
                            ,getContent(six.get(i).getState())
                            ,getContent(seven.get(i).getState())
                            ,getContent(eight.get(i).getState())
                            ,getContent(nine.get(i).getState()));
                    addPosition(sb1,one.get(i));
                    addPosition(sb2,two.get(i));
                    addPosition(sb3,three.get(i));
                    addPosition(sb4,four.get(i));
                    addPosition(sb5,five.get(i));
                    addPosition(sb6,six.get(i));
                    addPosition(sb7,seven.get(i));
                    addPosition(sb8,eight.get(i));
                    addPosition(sb9,nine.get(i));
                }
                addcollect(sb1, sb2, sb3, sb4, sb5, sb6, sb7, sb8, sb9);
                if (tableCallback!=null){
                    tableCallback.onFInish();
                }
            }
        });

    }
    private void addcollect(List<Integer> sb1, List<Integer> sb2, List<Integer> sb3, List<Integer> sb4, List<Integer> sb5, List<Integer> sb6, List<Integer> sb7, List<Integer> sb8, List<Integer> sb9){
        if (tvCollectTitle.getVisibility() == GONE){
            tvCollectTitle.setVisibility(VISIBLE);
        }
        if (tvCollectContent.getVisibility() == GONE){
            tvCollectContent.setVisibility(VISIBLE);
        }
        if (sb1.isEmpty()&&sb2.isEmpty()&&sb3.isEmpty()&&sb4.isEmpty()&&sb5.isEmpty()&&sb6.isEmpty()&&sb7.isEmpty()&&sb8.isEmpty()&&sb9.isEmpty()){
            tvCollectContent.setText("      无零值片。");
        }else{
            StringBuilder sb = new StringBuilder();
            if (!sb1.isEmpty()){
                sb.append("      A相左串有").append(sb1.size()).append("片零值，分别是").append(listToString(sb1)).append("。\n");
            }
            if (!sb2.isEmpty()){
                sb.append("      A相中串有").append(sb2.size()).append("片零值，分别是").append(listToString(sb2)).append("。\n");
            }
            if (!sb3.isEmpty()){
                sb.append("      A相右串有").append(sb3.size()).append("片零值，分别是").append(listToString(sb3)).append("。\n");
            }
            if (!sb4.isEmpty()){
                sb.append("      B相左串有").append(sb4.size()).append("片零值，分别是").append(listToString(sb4)).append("。\n");
            }
            if (!sb5.isEmpty()){
                sb.append("      B相中串有").append(sb5.size()).append("片零值，分别是").append(listToString(sb5)).append("。\n");
            }
            if (!sb6.isEmpty()){
                sb.append("      B相右串有").append(sb6.size()).append("片零值，分别是").append(listToString(sb6)).append("。\n");
            }
            if (!sb7.isEmpty()){
                sb.append("      C相左串有").append(sb7.size()).append("片零值，分别是").append(listToString(sb7)).append("。\n");
            }
            if (!sb8.isEmpty()){
                sb.append("      C相中串有").append(sb8.size()).append("片零值，分别是").append(listToString(sb8)).append("。\n");
            }
            if (!sb9.isEmpty()){
                sb.append("      C相右串有").append(sb9.size()).append("片零值，分别是").append(listToString(sb9)).append("。\n");
            }
            tvCollectContent.setText(sb.toString());
        }
    }
    private String listToString(List<Integer> list){
        if (list.isEmpty()){
            return "";
        }else{
            StringBuilder sb = new StringBuilder();
            for (int i = 0;i<list.size();i++){
                if (i == list.size()-1){
                    sb.append(list.get(i));
                }else{
                    sb.append(list.get(i)).append("、");
                }
            }
            return sb.toString();
        }
    }
    private void addPosition(List<Integer> sb ,ZeroDetectionEntity zeroDetectionEntity){
        if (zeroDetectionEntity.getState() == 0){
            sb.add(zeroDetectionEntity.getPosition());
        }
    }
    private void addRow(String i, String one, String two, String three, String four, String five, String six, String seven, String eight, String nine){
        TableItemView tableItemView = new TableItemView(getContext());
        tableItemView.setDate(i,one,two,three,four,five,six,seven,eight,nine);
        TableRow childAt = (TableRow) tableItemView.getChildAt(0);
        tableItemView.removeViewAt(0);
        tableRoot.addView(childAt);

    }
    private String getContent(int state){
        if (state <0){
            return "/";
        }else{
            return String.valueOf(state);
        }
    }
    private TableCallback tableCallback;

    public void setTableCallback(TableCallback tableCallback) {
        this.tableCallback = tableCallback;
    }

    public void clearDate() {
        tvAddress.setText("");
        tvLineName.setText("");
        tvTowerNum.setText("");
        tvInstall.setText("");
        clearContent();
        tvCollectContent.setText("");
    }

    public interface TableCallback{
        void onFInish();
    }
    private void disposalPhase(List<PhaseInfo> phaseInfos){
        //遍历所有数据  拿到最大的绝缘子索引
        int maxIndex = getMaxIndex(phaseInfos);
        //判断是否有上相
        PhaseInfo phaseInfo = hasPhaseInfo(phaseInfos, 1);
        if (phaseInfo==null){
            //如果没有
            phaseInfo = new PhaseInfo();
            phaseInfo.phase = 1;
            phaseInfo.insulatorInfos = new ArrayList<>();
            phaseInfos.add(phaseInfo);
        }
        disposalBunch(phaseInfo.insulatorInfos,maxIndex);
        //判断是否有中相
        PhaseInfo phaseInfo1 = hasPhaseInfo(phaseInfos, 2);
        if (phaseInfo1==null){
            //如果没有
            phaseInfo1 = new PhaseInfo();
            phaseInfo1.phase = 2;
            phaseInfo1.insulatorInfos = new ArrayList<>();
            phaseInfos.add(phaseInfo1);
        }
        disposalBunch(phaseInfo1.insulatorInfos,maxIndex);
        //判断是否有下相
        PhaseInfo phaseInfo2 = hasPhaseInfo(phaseInfos, 3);
        if (phaseInfo2==null){
            //如果没有
            phaseInfo2 = new PhaseInfo();
            phaseInfo2.phase = 3;
            phaseInfo2.insulatorInfos = new ArrayList<>();
            phaseInfos.add(phaseInfo2);
        }
        disposalBunch(phaseInfo2.insulatorInfos,maxIndex);
        Collections.sort(phaseInfos, comparator2);
    }
    private Comparator<PhaseInfo> comparator2 = new Comparator<PhaseInfo>() {
        @Override
        public int compare(PhaseInfo object1, PhaseInfo object2) {
            return object1.phase-object2.phase;
        }
    };
    private void disposalBunch(List<BunchInfo> list,int max){
        //判断是否有左串
        BunchInfo bunchInfo = hasBunchInfo(list, 1);
        if (bunchInfo == null){
            bunchInfo = new BunchInfo();
            bunchInfo.insulator = 1;
            bunchInfo.insulatorInfos = new ArrayList<>();
            list.add(bunchInfo);
        }
        bunchInfo.insulatorInfos = disposalEvery(bunchInfo.insulatorInfos, max);
        //判断是否有中串
        BunchInfo bunchInfo1 = hasBunchInfo(list, 2);
        if (bunchInfo1 == null){
            bunchInfo1 = new BunchInfo();
            bunchInfo1.insulator = 2;
            bunchInfo1.insulatorInfos = new ArrayList<>();
            list.add(bunchInfo1);
        }
        bunchInfo1.insulatorInfos = disposalEvery(bunchInfo1.insulatorInfos,max);
        //判断是否有右串
        BunchInfo bunchInfo2 = hasBunchInfo(list, 3);
        if (bunchInfo2 == null){
            bunchInfo2 = new BunchInfo();
            bunchInfo2.insulator = 3;
            list.add(bunchInfo2);
        }
        if ( bunchInfo2.insulatorInfos == null){
            bunchInfo2.insulatorInfos = new ArrayList<>();
        }
        bunchInfo2.insulatorInfos = disposalEvery(bunchInfo2.insulatorInfos,max);
        Collections.sort(list, comparator1);
    }
    private Comparator<BunchInfo> comparator1 = new Comparator<BunchInfo>() {
        @Override
        public int compare(BunchInfo object1, BunchInfo object2) {
            return object1.insulator-object2.insulator;
        }
    };
    private Comparator<ZeroDetectionEntity> comparator = new Comparator<ZeroDetectionEntity>() {
        @Override
        public int compare(ZeroDetectionEntity object1, ZeroDetectionEntity object2) {
            return object1.getPosition()-object2.getPosition();
        }
    };
    private  List<ZeroDetectionEntity> disposalEvery(List<ZeroDetectionEntity> zeroDetectionEntities,int max){
        if (zeroDetectionEntities==null){
            zeroDetectionEntities = new ArrayList<>();
        }
        List<ZeroDetectionEntity> temp = new ArrayList<>(max);
        for (int i = 0; i < max; i++) {
            temp.add(null);
        }
        for (ZeroDetectionEntity zeroDetectionEntity:zeroDetectionEntities){
            temp.set(zeroDetectionEntity.getPosition()-1,zeroDetectionEntity);
        }
        // 遍历列表，将 null 替换为新对象
        for (int i = 0; i < max; i++) {
            if (temp.get(i) == null) {
                temp.set(i,new ZeroDetectionEntity(i+1,-1));
            }
        }
        zeroDetectionEntities = temp;
        Collections.sort(zeroDetectionEntities, comparator);
        return temp;
    }
    private BunchInfo hasBunchInfo(List<BunchInfo> list,int bunch){
        if (list == null||list.size()<=0){
            return null;
        }
        for (BunchInfo bunchInfo:list){
            if (bunchInfo.insulator == bunch){
                return bunchInfo;
            }
        }
        return null;
    }
    private PhaseInfo hasPhaseInfo(List<PhaseInfo> phaseInfos,int phase){
        if (phaseInfos == null||phaseInfos.size()<=0){
            return null;
        }
        for (PhaseInfo phaseInfo:phaseInfos){
            if (phaseInfo.phase == phase){
                return phaseInfo;
            }
        }
        return null;
    }
    private int getMaxIndex(List<PhaseInfo> phaseInfos){
        int max = 0;
        for (int i = 0;i<phaseInfos.size();i++){
            List<BunchInfo> insulatorInfos = phaseInfos.get(i).insulatorInfos;
            if (insulatorInfos!=null&&insulatorInfos.size()>0){
                for (BunchInfo insulatorInfo : phaseInfos.get(i).insulatorInfos) {
                    if (insulatorInfo.insulatorInfos!=null&&insulatorInfo.insulatorInfos.size()>0){
                        for (ZeroDetectionEntity info : insulatorInfo.insulatorInfos) {
                            if (info.getPosition()>max){
                                max = info.getPosition();
                            }
                        }

                    }
                }
            }
        }
        return max;
    }
}
